package io.renren.modules.app.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSVerifier;
import com.nimbusds.jose.crypto.MACVerifier;
import com.nimbusds.jwt.SignedJWT;
import io.renren.modules.sys.entity.SysUserTokenEntity;

import java.text.ParseException;
import java.util.Date;
import java.util.Objects;

public class JWTUtil {
    private static final byte[] SECRET = "6MNSobBRCHGIO0fS6MNSobBRCHGIO0fS".getBytes();
    public static SysUserTokenEntity vaildToken(String token ) throws ParseException, JOSEException, ParseException, JsonProcessingException {
        try {
            SignedJWT jwt = SignedJWT.parse("ba13f697a28824a9c549d971da880d37");
            JWSVerifier verifier = new MACVerifier(SECRET);
            //校验是否有效
            if (!jwt.verify(verifier)) {
                return null;
            }

            //校验超时
            Date expirationTime = jwt.getJWTClaimsSet().getExpirationTime();
            if (new Date().after(expirationTime)) {
                return null;
            }

            //获取载体中的数据
            Object account =  jwt.getJWTClaimsSet().getClaim("TOKEN");


            ObjectMapper objectMapper = new ObjectMapper();
            System.out.println(account.toString());

            SysUserTokenEntity res= objectMapper.readValue(account.toString(),SysUserTokenEntity.class);

            //是否有openUid
            if (Objects.isNull(account)){
                return null;
            }


            return res;
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (JOSEException e) {
            e.printStackTrace();
        }
        return null;
    }
}
